<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-server"></i>
              Docker服务器配置
            </h1>
            <p class="page-subtitle">管理Docker服务器连接配置</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.total_docker_servers || 0 }}</div>
              <div class="stat-label">Docker服务器</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.total_containers || 0 }}</div>
              <div class="stat-label">容器总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.connected_servers || 0 }}</div>
              <div class="stat-label">已连接</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="search-filters glass-effect">
        <el-form inline class="search-form">
          <el-form-item>
            <el-button type="primary" @click="refreshServers" class="glass-button refresh-button" :loading="loading">
              <i class="fa fa-refresh"></i>
              刷新状态
            </el-button>
            <el-button @click="showAddDockerServer" class="glass-button add-button">
              <i class="fa fa-plus"></i>
              添加Docker服务器
            </el-button>
            <el-button @click="testAllConnections" class="glass-button import-button" :loading="testing">
              <i class="fa fa-plug"></i>
              测试所有连接
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- Docker服务器列表 -->
      <div class="audit-table-section glass-effect">
        <div class="section-title">
          <i class="fa fa-docker"></i>
          Docker服务器列表
        </div>

        <el-table
          :data="dockerServers"
          style="width: 100%"
          v-loading="loading"
          row-class-name="audit-row"
          class="audit-table"
        >
          <el-table-column prop="name" label="服务器名称" min-width="150">
            <template #default="scope">
              <div class="config-name">
                <i class="fa fa-docker"></i>
                {{ scope.row.name }}
                <el-tag v-if="scope.row.is_default" type="success" size="small" style="margin-left: 8px;">默认</el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="host" label="服务器地址" min-width="200" />

          <el-table-column prop="port" label="端口" width="80" />

          <el-table-column prop="connection_status" label="连接状态" width="120">
            <template #default="scope">
              <el-tag
                :type="getStatusType(scope.row.connection_status)"
                size="small"
              >
                {{ getStatusText(scope.row.connection_status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="docker_version" label="Docker版本" width="120">
            <template #default="scope">
              <span class="version-text">
                {{ scope.row.docker_version || '未知' }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="total_containers" label="容器数量" width="100">
            <template #default="scope">
              <el-tag type="info" size="small">
                {{ scope.row.total_containers || 0 }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="last_check_time" label="最后检查" width="150">
            <template #default="scope">
              <span class="time-text">
                {{ formatTime(scope.row.last_check_time) }}
              </span>
            </template>
          </el-table-column>



          <el-table-column label="操作" width="330" :show-overflow-tooltip="false">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  @click="testConnection(scope.row)"
                  size="small"
                  class="glass-button import-button"
                  :loading="scope.row.testing"
                >
                  <i class="fa fa-plug"></i>
                  测试连接
                </el-button>
                <el-button
                  @click="editServer(scope.row)"
                  size="small"
                  class="glass-button sync-button"
                >
                  <i class="fa fa-edit"></i>
                  编辑
                </el-button>
                <el-button
                  @click="deleteServer(scope.row)"
                  size="small"
                  class="glass-button delete-button"
                >
                  <i class="fa fa-trash"></i>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- Docker服务器配置对话框 -->
    <el-dialog
      v-model="dockerDialogVisible"
      :title="dockerDialogTitle"
      width="600px"
      class="glass-dialog"
    >
      <el-form :model="dockerForm" :rules="dockerRules" ref="dockerFormRef" label-width="120px">
        <el-form-item label="服务器名称" prop="name">
          <el-input v-model="dockerForm.name" placeholder="请输入服务器名称" />
        </el-form-item>
        <el-form-item label="服务器地址" prop="host">
          <el-input v-model="dockerForm.host" placeholder="192.168.1.100" />
        </el-form-item>
        <el-form-item label="SSH端口" prop="ssh_port">
          <el-input v-model="dockerForm.ssh_port" placeholder="22" type="number" />
        </el-form-item>
        <el-form-item label="Docker端口" prop="docker_port">
          <el-input v-model="dockerForm.docker_port" placeholder="2376" type="number" />
        </el-form-item>
        <el-form-item label="SSH用户名" prop="ssh_username">
          <el-input v-model="dockerForm.ssh_username" placeholder="请输入SSH用户名" />
        </el-form-item>
        <el-form-item label="SSH密码" prop="ssh_password">
          <el-input v-model="dockerForm.ssh_password" type="password" placeholder="请输入SSH密码" show-password />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dockerForm.description" type="textarea" placeholder="服务器描述" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="dockerForm.is_active">启用服务器</el-checkbox>
          <el-checkbox v-model="dockerForm.is_default">设为默认服务器</el-checkbox>
          <el-checkbox v-model="dockerForm.use_ssh_tunnel">使用SSH隧道</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dockerDialogVisible = false" class="glass-button">取消</el-button>
          <el-button type="primary" @click="saveDockerServer" class="glass-button add-button" :loading="saving">
            <i class="fa fa-save"></i>
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { dockerServerAPI } from '@/api/docker'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 响应式数据
const loading = ref(false)
const testing = ref(false)
const saving = ref(false)

// 统计数据
const statistics = reactive({
  total_docker_servers: 0,
  total_containers: 0,
  connected_servers: 0
})

// 服务器列表
const dockerServers = ref([])

// Docker服务器对话框
const dockerDialogVisible = ref(false)
const dockerDialogTitle = ref('')
const dockerFormRef = ref<FormInstance>()
const dockerForm = reactive({
  id: null,
  name: '',
  host: '',
  ssh_port: 22,
  docker_port: 2376,
  ssh_username: '',
  ssh_password: '',
  description: '',
  is_active: true,
  is_default: false,
  use_ssh_tunnel: true
})

const dockerRules: FormRules = {
  name: [
    { required: true, message: '请输入服务器名称', trigger: 'blur' }
  ],
  host: [
    { required: true, message: '请输入服务器地址', trigger: 'blur' }
  ],
  ssh_username: [
    { required: true, message: '请输入SSH用户名', trigger: 'blur' }
  ],
  ssh_password: [
    { required: true, message: '请输入SSH密码', trigger: 'blur' }
  ]
}

// 页面加载
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // TODO: 实现API调用
    await Promise.all([
      loadDockerServers(),
      loadStatistics()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载Docker服务器列表
const loadDockerServers = async () => {
  try {
    const response = await dockerServerAPI.getServers()
    const servers = response.data.results || response.data || []

    // 为每个服务器加载Harbor登录状态
    for (const server of servers) {
      try {
        const harborResponse = await dockerAPI.checkHarborLoginStatus(server.id)
        if (harborResponse.data.success) {
          server.harbor_logged_in = harborResponse.data.data.is_logged_in
          server.harbor_registry = harborResponse.data.data.registry
          server.harbor_username = harborResponse.data.data.username
        } else {
          server.harbor_logged_in = false
          server.harbor_registry = ''
          server.harbor_username = ''
        }
      } catch (error) {
        console.error(`加载服务器 ${server.name} 的Harbor状态失败:`, error)
        server.harbor_logged_in = false
        server.harbor_registry = ''
        server.harbor_username = ''
      }
    }

    dockerServers.value = servers
  } catch (error) {
    console.error('加载Docker服务器失败:', error)
    ElMessage.error('加载Docker服务器失败')
  }
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await dockerServerAPI.getStatistics()
    Object.assign(statistics, response.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 刷新服务器状态
const refreshServers = () => {
  loadData()
  ElMessage.success('服务器状态已刷新')
}

// 显示添加Docker服务器对话框
const showAddDockerServer = () => {
  resetDockerForm()
  dockerDialogTitle.value = '添加Docker服务器'
  dockerDialogVisible.value = true
}

// 重置Docker表单
const resetDockerForm = () => {
  Object.assign(dockerForm, {
    id: null,
    name: '',
    host: '',
    ssh_port: 22,
    docker_port: 2376,
    ssh_username: '',
    ssh_password: '',
    description: '',
    is_active: true,
    is_default: false,
    use_ssh_tunnel: true
  })
  dockerFormRef.value?.clearValidate()
}

// 测试连接
const testConnection = async (server: any) => {
  server.testing = true
  try {
    const response = await dockerServerAPI.testConnection(server.id)
    if (response.data.success) {
      ElMessage.success(`${server.name} 连接测试成功`)
    } else {
      ElMessage.error(`${server.name} 连接测试失败: ${response.data.message}`)
    }
    await loadDockerServers()
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error(`${server.name} 连接测试失败`)
  } finally {
    server.testing = false
  }
}

// 测试所有连接
const testAllConnections = async () => {
  testing.value = true
  try {
    const response = await dockerServerAPI.testAllConnections()
    if (response.data.success) {
      ElMessage.success('所有连接测试完成')
    } else {
      ElMessage.error('批量测试连接失败')
    }
    await loadDockerServers()
  } catch (error) {
    console.error('批量测试连接失败:', error)
    ElMessage.error('批量测试连接失败')
  } finally {
    testing.value = false
  }
}

// 编辑服务器
const editServer = (server: any) => {
  Object.assign(dockerForm, server)
  dockerDialogTitle.value = '编辑Docker服务器'
  dockerDialogVisible.value = true
}

// 保存Docker服务器
const saveDockerServer = async () => {
  if (!dockerFormRef.value) return

  try {
    await dockerFormRef.value.validate()
    saving.value = true

    const isEdit = !!dockerForm.id
    const formData = { ...dockerForm }

    if (isEdit) {
      await dockerServerAPI.updateServer(dockerForm.id, formData)
    } else {
      await dockerServerAPI.createServer(formData)
    }

    ElMessage.success(isEdit ? '服务器更新成功' : '服务器创建成功')
    dockerDialogVisible.value = false
    await loadDockerServers()
    await loadStatistics()
  } catch (error) {
    console.error('保存Docker服务器失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 删除服务器
const deleteServer = async (server: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除服务器 "${server.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await dockerServerAPI.deleteServer(server.id)
    ElMessage.success('服务器删除成功')
    await loadDockerServers()
    await loadStatistics()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务器失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 工具函数
const getStatusType = (status: string) => {
  switch (status) {
    case 'connected': return 'success'
    case 'disconnected': return 'danger'
    case 'error': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'connected': return '已连接'
    case 'disconnected': return '连接失败'
    case 'error': return '错误'
    default: return '未知'
  }
}

const formatTime = (time: string) => {
  if (!time) return '从未'
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
/* 使用与Zabbix服务器配置页面完全相同的样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section h1 {
  color: rgba(255, 255, 255, 0.95);
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.title-section h1 i {
  color: #a4f4ba;
  margin-right: 12px;
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #a4f4ba;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.search-filters {
  margin-bottom: 30px;
  padding: 20px;
}

.search-form {
  margin: 0;
}

.audit-table-section {
  padding: 30px;
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.section-title i {
  color: #a4f4ba;
}

.config-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.config-name i {
  color: #00eaff;
}

.time-text, .version-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

/* 工具栏按钮样式 - 完全照抄Zabbix服务器配置页面 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }

  /* 刷新按钮 - 紫色 */
  &.refresh-button {
    background: rgba(138, 43, 226, 0.2) !important;
    border-color: rgba(138, 43, 226, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(138, 43, 226, 0.3) !important;
      border-color: rgba(138, 43, 226, 0.6) !important;
      box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
    }

    i {
      color: #8a2be2 !important;
    }
  }

  /* 同步按钮 - 蓝色 */
  &.sync-button {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
      box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
    }

    i {
      color: #3b82f6 !important;
    }
  }

  /* 添加按钮 - 绿色 */
  &.add-button {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
      box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
    }

    i {
      color: #22c55e !important;
    }
  }

  /* 导入按钮 - 青色 */
  &.import-button {
    background: rgba(6, 182, 212, 0.2) !important;
    border-color: rgba(6, 182, 212, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(6, 182, 212, 0.3) !important;
      border-color: rgba(6, 182, 212, 0.6) !important;
      box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3) !important;
    }

    i {
      color: #06b6d4 !important;
    }
  }

  /* 删除按钮 - 红色 */
  &.delete-button {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: rgba(239, 68, 68, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(239, 68, 68, 0.3) !important;
      border-color: rgba(239, 68, 68, 0.6) !important;
      box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3) !important;
    }

    i {
      color: #ef4444 !important;
    }
  }
}

/* 表格样式 */
:deep(.audit-table) {
  background: transparent !important;

  .el-table__header {
    background: rgba(164, 244, 186, 0.1) !important;
  }

  .el-table__header th {
    background: transparent !important;
    border-bottom: 1px solid rgba(164, 244, 186, 0.3) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    font-weight: 600 !important;
  }

  .el-table__body tr {
    background: transparent !important;

    &:hover {
      background: rgba(164, 244, 186, 0.05) !important;
    }
  }

  .el-table__body td {
    border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
    color: rgba(255, 255, 255, 0.8) !important;
  }
}

/* 对话框样式 */
:deep(.glass-dialog) {
  .el-dialog {
    background: rgba(30, 30, 30, 0.95) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 12px !important;
    backdrop-filter: blur(20px) !important;
  }

  .el-dialog__header {
    background: rgba(164, 244, 186, 0.1) !important;
    border-bottom: 1px solid rgba(164, 244, 186, 0.2) !important;
    border-radius: 12px 12px 0 0 !important;
  }

  .el-dialog__title {
    color: rgba(255, 255, 255, 0.95) !important;
    font-weight: 600 !important;
  }

  .el-dialog__body {
    background: transparent !important;
    color: rgba(255, 255, 255, 0.9) !important;
  }

  .el-form-item__label {
    color: rgba(255, 255, 255, 0.8) !important;
  }

  .el-input__wrapper {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    border-radius: 6px !important;
  }

  .el-input__inner {
    background: transparent !important;
    color: rgba(255, 255, 255, 0.9) !important;
  }

  .el-textarea__inner {
    background: rgba(164, 244, 186, 0.1) !important;
    border: 1px solid rgba(164, 244, 186, 0.3) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    border-radius: 6px !important;
  }
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: nowrap;
}

.action-buttons .glass-button {
  padding: 8px 16px !important;
  font-size: 12px;
  white-space: nowrap;
  width: auto !important;
}
</style>
